package cn.dzhang.spring.web.auth;

import java.text.MessageFormat;
import java.util.Locale;

import javax.annotation.Resource;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.dzhang.spring.model.User;
import cn.dzhang.spring.service.UserService;

public class SpringAuthenticationProvider extends
		AbstractUserDetailsAuthenticationProvider {

	@Resource
	private UserService us;

	// @Autowired
	// @Qualifier("securityMessageSource")
	// private MessageSource messageSource;

	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		if (userDetails instanceof SpringUser) {
			SpringUser user = (SpringUser) userDetails;
			if (!user.getPassword().equals(authentication.getCredentials())) {
				String msg = SpringSecurityMessageSource
						.getAccessor()
						.getMessage(
								"PasswordComparisonAuthenticator.badCredentials");
				throw new BadCredentialsException(msg);
			}
		}
	}

	@Override
	protected UserDetails retrieveUser(String username,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		User user = us.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException(MessageFormat.format(
					SpringSecurityMessageSource.getAccessor().getMessage(
							"DigestAuthenticationFilter.usernameNotFound",
							new String[] { username }, Locale.getDefault()),
					username));
		}

		SpringUser userDetails = new SpringUser(user);

		return userDetails;
	}

}
